package org.devgframwork.datasync.admin.support.init.impl;

import org.devgframwork.datasync.admin.support.init.AbstractInit;
import org.devgframwork.datasync.core.entity.JdbcConfig;
import org.devgframwork.datasync.core.support.DataSourceMemory;
import org.devgframwork.datasync.core.utils.CommonUtil;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.devgframwork.datasync.admin.rabbit.service.JdbcConfigService;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.List;

/**
 * @Description
 * @auther dh
 * @date 2022/1/5 14:36
 */
@Slf4j
public class JdbcInit extends AbstractInit {


    public JdbcInit(AbstractInit nextAbstractInit) {
        super(nextAbstractInit);
    }

    @Override
    public void initComponent() {
        JdbcConfigService jdbcConfigService = DataSourceMemory.applicationContext.getBean(JdbcConfigService.class);
        List<JdbcConfig> jdbcConfigList = jdbcConfigService.getJdbcConfigList();
        if (CommonUtil.isEmpty(jdbcConfigList)) {
            log.warn("jdbcConfigList is empty");
            return;
        }
        for (JdbcConfig jdbcConfig : jdbcConfigList) {
            String keyName = jdbcConfig.getKeyName();
            HikariDataSource dataSource = createHikariDataSource(jdbcConfig, keyName);
            JdbcTemplate jdbcTemplate = createJdbcTemplate(dataSource);
            DataSourceMemory.jdbcTemplateMap.put(keyName, jdbcTemplate);
        }
        log.info("init jdbc success");
    }

    private HikariDataSource createHikariDataSource(JdbcConfig config, String connectionName) {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(config.getDriverClassName());
        dataSource.setJdbcUrl(config.getUrl());
        dataSource.setUsername(config.getDbUsername());
        dataSource.setPassword(config.getDbPassword());
        dataSource.setPoolName(connectionName);
        Integer maxActive = config.getMaxActive() == null ? 50 : config.getMaxActive();
        dataSource.setMaximumPoolSize(maxActive);
        dataSource.setMinimumIdle(maxActive / 2);
        dataSource.setIdleTimeout(30000L);
        dataSource.setAutoCommit(true);
        dataSource.setMaxLifetime(1800000L);
        dataSource.setConnectionTimeout(30000L);
        dataSource.setConnectionTestQuery("select 1");
        return dataSource;
    }

    private JdbcTemplate createJdbcTemplate(DataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setIgnoreWarnings(true);
        jdbcTemplate.setDataSource(dataSource);
        jdbcTemplate.setQueryTimeout(30);
        return jdbcTemplate;
    }
}
